const express = require("express");
const router = express.Router();
const adminServices = require("../../services/adminService");
const { asyncHandler } = require("../../utils/routerHelper");
// const crypt = require('../../utils/crypt');
const jwt = require("../../utils/jwt");
// 添加管理员
router.post(
  "/add",
  asyncHandler(async (req, res, next) => {
    return await adminServices.addAdmin(req.body);
  })
);

// 更新管理员
router.put(
  "/:id",
  asyncHandler(async (req, res, next) => {
    return await adminServices.updateAdmin(+req.params.id, req.body);
  })
);

// 删除管理员
router.delete(
  "/:id",
  asyncHandler(async (req, res, next) => {
    return await adminServices.deleteAdmin(+req.params.id);
  })
);

// 查询管理员
router.get(
  "/:id",
  asyncHandler(async (req, res, next) => {
    return await adminServices.getAdminById(+req.params.id);
  })
);

// 查询所有管理员
router.get(
  "/:page/:limit",
  asyncHandler(async (req, res, next) => {
    const { page, limit } = req.params;
    return await adminServices.getAdmins(page && +page, limit && +limit);
  })
);

// 登录
router.post(
  "/login",
  asyncHandler(async (req, res, next) => {
    const { account, password } = req.body;
    const admin = await adminServices.login(account, password);
    console.log(typeof admin)
    let result = { ...JSON.parse(JSON.stringify(admin)) };
    if (admin) {
      // const value = crypt.encrypt(admin.id + '');
      const token = jwt.encryptToken({ id: admin.id });
      // console.log('token',value);
      // res.cookie('token', value, {
      //   path: '/',
      //   domain: 'localhost',
      //   maxAge: 1000 * 60 * 60 * 24 * 7,
      //   httpOnly: true
      // })
      res.header("Authorization", token);
      result = { ...result, token };
    }
    return result;
  })
);
module.exports = router;
